$(function(){
	
	var tbody=$("tbody");
	
	function renderer(target,json) {

		var obj = {};
		obj.render = function() {
			target.empty();
			json.forEach((item)=>{
				var tr=$("<tr></tr>");
				var td1=$("<td></td>");
				td1.html(item.name);
				var td2=$("<td></td>");
				if(item.sex==true){
					td2.html("Male");
				}else{
					td2.html("Female");
				}
				var td3=$("<td></td>");
				td3.html(item.sal);
				var td4=$("<td></td>");
				td4.html(formatDateTime(item.birth));
				var td5=$("<td></td>");
				var td5Text = "<button type='button' id='deleteBtn' class='btn btn-danger btn-block' bid='"+item.id+"' >Delete</button>";
				td5.html(td5Text);
				var td6=$("<td></td>");
				var td6Text = "<button type='button' id='updateBtn' class='btn btn-success btn-block' bid='"+item.id+"' >Update</button>";
				td6.html(td6Text);
				
				tr.append(td1);
				tr.append(td2);
				tr.append(td3);
				tr.append(td4);
				tr.append(td5);
				tr.append(td6);
				$(target).append(tr);
			});
			
			// delete customer
			$("button[id=deleteBtn]").on("click",function () {
				var id = $(this).attr("bid");
				console.log(id)
				var data={"id":id};
				asyncRequest("/springMVC_day7/customers/delete","DELETE",data,$(tbody));
			});
			
			// update customer
			$("button[id=updateBtn]").on("click",function () {
				var id = $(this).attr("bid");
				console.log(id);
				var data={"id":id};
				requestAndOpenModal("/springMVC_day7/customers/get","post",data);
			});
		};
		return obj;
	};

	// get all customers
	function getAllCustomers(target){

		asyncRequest("/springMVC_day7/customers/listAll","GET",null,target);
	}
	getAllCustomers($(tbody));

	// add one customer
	$("form button").on("click",function(){
		console.log("ddd");
		var name=$("input[name=name]").val();
		var sex=$("input[name=sex]:checked").val();
		var sal=$("input[name=sal]").val();
		var birth=$("input[name=birth]").val();
		if(name.length==0||sex.leng==0||sal.length==0||birth.length==0){
			swal("It's empty, please check!", "Please check all fields.");
			return;
		}
		var customer={
			id:"null",
			name:name,
			sex:sex,
			sal:sal,
			birth:birth
		};
		console.log(customer);
		asyncRequest("/springMVC_day7/customers/add","PUT",customer,$(tbody));
	})

	// async request and render page
	function asyncRequest(url,type,data,target) {

		$.ajax({
			url:url,
			type : type,
			data : JSON.stringify(data),
			contentType : "application/json",
		}).done(function(json) {
			console.log(json)
			renderer(target,json).render();
			clearForm($('#fm'));
		});
	};
	
	// request and open Modal
	function requestAndOpenModal(url,type,data) {

		$.ajax({
			url:url,
			type : type,
			data : JSON.stringify(data),
			contentType : "application/json",
		}).done(function(json) {
			clearForm($('#fm'));
			$("input[name=u_id]").val(json.id);
			$("input[name=u_name]").val(json.name);
			if(json.sex==true){
				$("input[name=u_sex]").first().attr("checked",true);
			}else{
				$("input[name=u_sex]").last().attr("checked",true);
			}
			$("input[name=u_sal]").val(json.sal);
			$("input[name=u_birth]").val(formatDateTime(json.birth));
			$('#myModal').modal('show')
		});
	};
	
	$('#modalBtn').on('hide.bs.modal', function () {
		  // 执行一些动作...
		clearForm($('#fm'));
	})
		
	$('#modalBtn').on('hidden.bs.modal', function () {
			// 执行一些动作...
		clearForm($('#fm'));
	})
	
	function clearForm(form) {
	    // input清空
	    $(':input', form).each(function () {
	        var type = this.type;
	        var tag = this.tagName.toLowerCase(); // normalize case
	        if (type == 'text' || type == 'password' || tag == 'textarea')
	            this.value = "";
	            // 多选checkboxes清空
	            // select 下拉框清空
	        else if (type == 'radio')
	            $(this).removeAttr("checked");
	    });
	};
	
	// update customer
	$("#modalBtn").on("click",function(){
		var name=$("input[name=u_name]").val();
		var sex=$("input[name=u_sex]:checked").val();
		var sal=$("input[name=u_sal]").val();
		var birth=$("input[name=u_birth]").val();
		var uid=$("input[name=u_id]").val();
		var updateCustomer={
			id:uid,
			name:name,
			sex:sex,
			sal:sal,
			birth:birth
		};
		console.log(updateCustomer);
		asyncRequest("/springMVC_day7/customers/update","POST",updateCustomer,$(tbody));
		$('#myModal').modal('hide');
	})
	
	// format time
	function formatDateTime(inputTime) {    
	    var date = new Date(inputTime);  
	    var y = date.getFullYear();    
	    var m = date.getMonth() + 1;    
	    m = m < 10 ? ('0' + m) : m;    
	    var d = date.getDate();    
	    d = d < 10 ? ('0' + d) : d;     
	    return y + '-' + m + '-' + d;    
	};
})